<?php

class ecrmUpdatePerformanceTask extends sfBaseTask
{
  protected function configure()
  {
    // add your own arguments here
    $this->addArguments(array(
      new sfCommandArgument('fileName', sfCommandArgument::REQUIRED, 'The file to process'),
      new sfCommandArgument('fileType', sfCommandArgument::REQUIRED, 'The reaction type of the file'),
      new sfCommandArgument('campaignId', sfCommandArgument::REQUIRED, 'The campaignId'),
    ));

    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application name'),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
      // add your own options here
    ));

    $this->namespace        = 'ecrm';
    $this->name             = 'updatePerformance';
    $this->briefDescription = '';
    $this->detailedDescription = <<<EOF
The [ecrm:updatePerformance|INFO] task does things.
Call it with:

  [php symfony ecrm:updatePerformance|INFO]
EOF;
  }

  protected function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = $databaseManager->getDatabase($options['connection'])->getConnection();

    // add your code here
    $parseVars = array();
    switch($arguments['fileType']) {
      case 'selected':
        $parseVars['sourceField'] = 4;
        $parseVars['saveFields'] = array(
          1 => 'member_id',
          2 => 'client_id',
          3 => 'email',
        );
        $this->parseSelected($parseVars, $arguments);
        break;
      case 'hard_bounce':
        $parseVars['saveFields'] = array(
          5 => 'hard_bounce_date',
          6 => 'hard_bounce_status_code',
          7 => 'hard_bounce_smtp_response',
          8 => 'hard_bounce_apparently_from',
          3 => 'email',
        );
        $this->parseHardBounce($parseVars, $arguments);
        break;
      case 'soft_bounce':
        $parseVars['saveFields'] = array(
          5 => 'soft_bounce_date',
          6 => 'soft_bounce_status_code',
          7 => 'soft_bounce_smtp_response',
          8 => 'soft_bounce_apparently_from',
          3 => 'email',
        );
        $this->parseSoftBounce($parseVars, $arguments);
        break;
      case 'opened':
        $parseVars['saveFields'] = array(
          3 => 'email'
        );
        $this->parseOpened($parseVars, $arguments);
        break; 
      case 'clicked':
        $parseVars['saveFields'] = array(
          3 => 'email'
        );
        $this->parseClicked($parseVars, $arguments);
        break;
      case 'unsubscribed':
        $parseVars['saveFields'] = array(
          3 => 'unsubscribe_date',
          4 => 'email'
        );
        $this->parseUnsubscribed($parseVars, $arguments);
        break;
      case 'complaint':
        $parseVars['saveFields'] = array(
          1 => 'complaint_name',
          2 => 'complaint_date',
          6 => 'email'
        );
        $this->parseComplaint($parseVars, $arguments);
        break;
      case 'click_detail':
        $parseVars['saveFields'] = array(
          5 => 'link_name',
          6 => 'link_url',
          7 => 'click_date',
          3 => 'email'
        );
        $this->parseClickDetail($parseVars, $arguments);
        break;               
    }
    
  }

  private function parseSelected($parseVars, $arguments)
  {
    $handle = fopen(getcwd().'/web/uploads/'.$arguments['fileName'], 'r');
    if($handle) {
      try{
        $line = fgetcsv($handle);
        while (!feof($handle)) {
          $lineArray = fgetcsv($handle, 0, '|');
          //$lineArray = explode('|', $line);
          if($lineArray[$parseVars['sourceField']] != '') {
            $conn = Doctrine_Manager::connection();
            //$this->log(var_dump($parseVars['saveFields']));
            //$this->log('SELECT id, email FROM contant_information WHERE email = "'.$lineArray[array_search('email', $parseVars['saveFields'])].'"');
            $contact = $conn->execute('SELECT id, email FROM contant_information WHERE email = "'.$lineArray[array_search('email', $parseVars['saveFields'])].'"')->fetch(PDO::FETCH_ASSOC);
            if($contact) {
              $emailCampaignUser = new EmailCampaignUserDetails();
              $emailCampaignUser->set('email_campaign_id', $arguments['campaignId']);
              $emailCampaignUser->set('contant_information_id', $contact['id']);
              $tempSaveFields = $parseVars['saveFields'];
              unset($tempSaveFields[array_search('email', $tempSaveFields)]);
              foreach($tempSaveFields as $key=>$saveField) {
                if(isset($lineArray[$key]) && $lineArray[$key] != '') {
                  $emailCampaignUser->set($saveField, $lineArray[$key]);
                }
              }
              $emailCampaignUserId = $emailCampaignUser->save();
              $emailCampaignUserPerformance = new EmailCampaignUserPerformance();
              $emailCampaignUserPerformance->set('email_campaign_user_details_id', $emailCampaignUser->getId());
              $emailCampaignUserPerformance->set('selected', 'Yes');
              $emailCampaignUserPerformance->save();
              $emailCampaignUserPerformance->free(true);
              $emailCampaignUser->free(true);
              $emailCampaignUserPerformance = '';
              $emailCampaignUser = '';
              $conn = '';
              unset($emailCampaignUser, $emailCampaignUserPerformance, $conn);
            }
          }
        }     
      }
      catch(Exception $e) {
        $this->log($e->getMessage());
        exit();
      }

      
    }
  }

  private function parseHardBounce($parseVars, $arguments)
  {
    $handle = fopen(getcwd().'/web/uploads/'.$arguments['fileName'], 'r');
    if($handle) {
      try{
        $line = fgetcsv($handle);
        while (!feof($handle)) {
          $lineArray = fgetcsv($handle, 0, '|');
          $conn = Doctrine_Manager::connection();
          $contact = $conn->execute('SELECT id, email FROM contant_information WHERE email = "'.$lineArray[array_search('email', $parseVars['saveFields'])].'"')->fetch(PDO::FETCH_ASSOC);
          if($contact) {
            $emailCampaignUser = Doctrine_Core::getTable('EmailCampaignUserDetails')->findOneByContantInformationIdAndEmailCampaignId($contact['id'], $arguments['campaignId']);
            if($emailCampaignUser) {
              $tempSaveFields = $parseVars['saveFields'];
              unset($tempSaveFields[array_search('email', $tempSaveFields)]);
              foreach($tempSaveFields as $key=>$saveField) {
                if(isset($lineArray[$key]) && $lineArray[$key] != '') {
                  if($saveField == 'hard_bounce_date') {
                    $emailCampaignUser->set($saveField, date('Y-m-d', strtotime($lineArray[$key])));
                  }
                  else {
                    $emailCampaignUser->set($saveField, $lineArray[$key]); 
                  }
                }
              }
              $emailCampaignUser->save();
              $emailCampaignUserPerformance = Doctrine_Core::getTable('EmailCampaignUserPerformance')->findOneBy('email_campaign_user_details_id', $emailCampaignUser->getId());
              $emailCampaignUserPerformance->set('hard_bounce', 'Yes');
              $emailCampaignUserPerformance->save();
              $emailCampaignUserPerformance->free(true);
              $emailCampaignUser->free(true);
              $emailCampaignUserPerformance = '';
              $emailCampaignUser = '';
              $contact = '';
              $conn = '';
              unset($emailCampaignUser, $emailCampaignUserPerformance, $contact, $conn);
            } 
            }
        }     
      }
      catch(Exception $e) {
        $this->log($e->getLine());
        $this->log($e->getFile());
        $this->log($e->getMessage());
        exit();
      }

      
    }
  }

  private function parseSoftBounce($parseVars, $arguments)
  {
    $handle = fopen(getcwd().'/web/uploads/'.$arguments['fileName'], 'r');
    if($handle) {
      try{
        $line = fgetcsv($handle);
        while (!feof($handle)) {
          $lineArray = fgetcsv($handle, 0, '|');
          $conn = Doctrine_Manager::connection();
          $contact = $conn->execute('SELECT id, email FROM contant_information WHERE email = "'.$lineArray[array_search('email', $parseVars['saveFields'])].'"')->fetch(PDO::FETCH_ASSOC);
          if($contact) {
            $emailCampaignUser = Doctrine_Core::getTable('EmailCampaignUserDetails')->findOneByContantInformationIdAndEmailCampaignId($contact['id'], $arguments['campaignId']);
            if($emailCampaignUser) {
              $tempSaveFields = $parseVars['saveFields'];
              unset($tempSaveFields[array_search('email', $tempSaveFields)]);
              foreach($tempSaveFields as $key=>$saveField) {
                if(isset($lineArray[$key]) && $lineArray[$key] != '') {
                  if($saveField == 'soft_bounce_date') {
                    $emailCampaignUser->set($saveField, date('Y-m-d', strtotime($lineArray[$key])));
                  }
                  else {
                    $emailCampaignUser->set($saveField, $lineArray[$key]); 
                  }
                }
              }
              $emailCampaignUser->save();
              $emailCampaignUserPerformance = Doctrine_Core::getTable('EmailCampaignUserPerformance')->findOneBy('email_campaign_user_details_id', $emailCampaignUser->getId());
              $emailCampaignUserPerformance->set('soft_bounce', 'Yes');
              $emailCampaignUserPerformance->save();
              $emailCampaignUserPerformance->free(true);
              $emailCampaignUser->free(true);
              $emailCampaignUserPerformance = '';
              $emailCampaignUser = '';
              $contact = '';
              $conn = '';
              unset($emailCampaignUser, $emailCampaignUserPerformance, $contact, $conn);
            } 
            }
        }     
      }
      catch(Exception $e) {
        $this->log($e->getLine());
        $this->log($e->getFile());
        $this->log($e->getMessage());
        exit();
      }

      
    }
  }

  private function parseOpened($parseVars, $arguments)
  {
    $handle = fopen(getcwd().'/web/uploads/'.$arguments['fileName'], 'r');
    if($handle) {
      try{
        $line = fgetcsv($handle);
        while (!feof($handle)) {
          $lineArray = fgetcsv($handle, 0, '|');
          $conn = Doctrine_Manager::connection();
          $contact = $conn->execute('SELECT id, email FROM contant_information WHERE email = "'.$lineArray[array_search('email', $parseVars['saveFields'])].'"')->fetch(PDO::FETCH_ASSOC);
          if($contact) {
            $emailCampaignUser = Doctrine_Core::getTable('EmailCampaignUserDetails')->findOneByContantInformationIdAndEmailCampaignId($contact['id'], $arguments['campaignId']);
            if($emailCampaignUser) {
              $emailCampaignUserPerformance = Doctrine_Core::getTable('EmailCampaignUserPerformance')->findOneBy('email_campaign_user_details_id', $emailCampaignUser->getId());
              if($emailCampaignUserPerformance->getHardBounce() != 'Yes' && $emailCampaignUserPerformance->getSoftBounce() != 'Yes') {
                $emailCampaignUserPerformance->set('opened', 'Yes');
                $emailCampaignUserPerformance->save(); 
              }
              $emailCampaignUserPerformance->free(true);
              $emailCampaignUser->free(true);
              $emailCampaignUserPerformance = '';
              $emailCampaignUser = '';
              $contact = '';
              $conn = '';
              unset($emailCampaignUser, $emailCampaignUserPerformance, $contact, $conn);
            } 
          }
        }
      }
      catch(Exception $e) {
        $this->log($e->getLine());
        $this->log($e->getFile());
        $this->log($e->getMessage());
        exit();
      }

      
    }
    else {
      $this->log('cant open file.');
    }
  }  

  
  private function parseClicked($parseVars, $arguments)
  {
    $handle = fopen(getcwd().'/web/uploads/'.$arguments['fileName'], 'r');
    if($handle) {
      try{
        $line = fgetcsv($handle);
        while (!feof($handle)) {
          $lineArray = fgetcsv($handle, 0, '|');
          $conn = Doctrine_Manager::connection();
          $contact = $conn->execute('SELECT id, email FROM contant_information WHERE email = "'.$lineArray[array_search('email', $parseVars['saveFields'])].'"')->fetch(PDO::FETCH_ASSOC);
          if($contact) {
            $emailCampaignUser = Doctrine_Core::getTable('EmailCampaignUserDetails')->findOneByContantInformationIdAndEmailCampaignId($contact['id'], $arguments['campaignId']);
            if($emailCampaignUser) {
              $emailCampaignUserPerformance = Doctrine_Core::getTable('EmailCampaignUserPerformance')->findOneBy('email_campaign_user_details_id', $emailCampaignUser->getId());
              if($emailCampaignUserPerformance->getHardBounce() != 'Yes' && $emailCampaignUserPerformance->getSoftBounce() != 'Yes' && $emailCampaignUserPerformance->getOpened() == 'Yes') {
                $emailCampaignUserPerformance->set('clicked', 'Yes');
                $emailCampaignUserPerformance->save(); 
              }
              $emailCampaignUserPerformance->free(true);
              $emailCampaignUser->free(true);
              $emailCampaignUserPerformance = '';
              $emailCampaignUser = '';
              $contact = '';
              $conn = '';
              unset($emailCampaignUser, $emailCampaignUserPerformance, $contact, $conn);
            } 
          }
        }
      }
      catch(Exception $e) {
        $this->log($e->getLine());
        $this->log($e->getFile());
        $this->log($e->getMessage());
        exit();
      }

      
    }
    else {
      $this->log('cant open file.');
    }
  }

  private function parseUnsubscribed($parseVars, $arguments)
  {
    $handle = fopen(getcwd().'/web/uploads/'.$arguments['fileName'], 'r');
    if($handle) {
      try{
        $line = fgetcsv($handle);
        while (!feof($handle)) {
          $lineArray = fgetcsv($handle, 0, '|');
          $conn = Doctrine_Manager::connection();
          $contact = $conn->execute('SELECT id, email FROM contant_information WHERE email = "'.$lineArray[array_search('email', $parseVars['saveFields'])].'"')->fetch(PDO::FETCH_ASSOC);
          if($contact) {
            $emailCampaignUser = Doctrine_Core::getTable('EmailCampaignUserDetails')->findOneByContantInformationIdAndEmailCampaignId($contact['id'], $arguments['campaignId']);
            if($emailCampaignUser) {
              if(is_null($emailCampaignUser->getHardBounceDate()) && is_null($emailCampaignUser->getSoftBounceDate())) {
                $tempSaveFields = $parseVars['saveFields'];
                unset($tempSaveFields[array_search('email', $tempSaveFields)]);
                foreach($tempSaveFields as $key=>$saveField) {
                  if(isset($lineArray[$key]) && $lineArray[$key] != '') {
                    if($saveField == 'unsubscribe_date') {
                      $emailCampaignUser->set($saveField, date('Y-m-d', strtotime($lineArray[$key])));
                    }
                    else {
                      $emailCampaignUser->set($saveField, $lineArray[$key]); 
                    }
                  }
                }
                $emailCampaignUser->save();
                $emailCampaignUserPerformance = Doctrine_Core::getTable('EmailCampaignUserPerformance')->findOneBy('email_campaign_user_details_id', $emailCampaignUser->getId());
                $emailCampaignUserPerformance->set('unsubscribed', 'Yes');
                $emailCampaignUserPerformance->save();
                $emailCampaignUserPerformance->free(true); 
              }
              $emailCampaignUser->free(true);
              $emailCampaignUserPerformance = '';
              $emailCampaignUser = '';
              $contact = '';
              $conn = '';
              unset($emailCampaignUser, $emailCampaignUserPerformance, $contact, $conn);
            } 
          }
        }     
      }
      catch(Exception $e) {
        $this->log($e->getLine());
        $this->log($e->getFile());
        $this->log($e->getMessage());
        exit();
      }

      
    }
  }

  private function parseComplaint($parseVars, $arguments)
  {
    $handle = fopen(getcwd().'/web/uploads/'.$arguments['fileName'], 'r');
    if($handle) {
      try{
        $line = fgetcsv($handle);
        while (!feof($handle)) {
          $lineArray = fgetcsv($handle, 0, '|');
          $conn = Doctrine_Manager::connection();
          $contact = $conn->execute('SELECT id, email FROM contant_information WHERE email = "'.$lineArray[array_search('email', $parseVars['saveFields'])].'"')->fetch(PDO::FETCH_ASSOC);
          if($contact) {
            $emailCampaignUser = Doctrine_Core::getTable('EmailCampaignUserDetails')->findOneByContantInformationIdAndEmailCampaignId($contact['id'], $arguments['campaignId']);
            if($emailCampaignUser) {
              if(is_null($emailCampaignUser->getHardBounceDate()) && is_null($emailCampaignUser->getSoftBounceDate())) {
                $tempSaveFields = $parseVars['saveFields'];
                unset($tempSaveFields[array_search('email', $tempSaveFields)]);
                foreach($tempSaveFields as $key=>$saveField) {
                  if(isset($lineArray[$key]) && $lineArray[$key] != '') {
                    if($saveField == 'complaint_date') {
                      $emailCampaignUser->set($saveField, date('Y-m-d', strtotime($lineArray[$key])));
                    }
                    else {
                      $emailCampaignUser->set($saveField, $lineArray[$key]); 
                    }
                  }
                }
                $emailCampaignUser->save();
                $emailCampaignUserPerformance = Doctrine_Core::getTable('EmailCampaignUserPerformance')->findOneBy('email_campaign_user_details_id', $emailCampaignUser->getId());
                $emailCampaignUserPerformance->set('complaint', 'Yes');
                $emailCampaignUserPerformance->save();
                $emailCampaignUserPerformance->free(true); 
              }
              $emailCampaignUser->free(true);
              $emailCampaignUserPerformance = '';
              $emailCampaignUser = '';
              $contact = '';
              $conn = '';
              unset($emailCampaignUser, $emailCampaignUserPerformance, $contact, $conn);
            } 
          }
        }     
      }
      catch(Exception $e) {
        $this->log($e->getLine());
        $this->log($e->getFile());
        $this->log($e->getMessage());
        exit();
      }

      
    }
  }

  private function parseClickDetail($parseVars, $arguments)
  {
    $handle = fopen(getcwd().'/web/uploads/'.$arguments['fileName'], 'r');
    if($handle) {
      try{
        $line = fgetcsv($handle);
        while (!feof($handle)) {
          $lineArray = fgetcsv($handle, 0, '|');
          $conn = Doctrine_Manager::connection();
          $contact = $conn->execute('SELECT id, email FROM contant_information WHERE email = "'.$lineArray[array_search('email', $parseVars['saveFields'])].'"')->fetch(PDO::FETCH_ASSOC);
          if($contact) {
            $emailCampaignUser = Doctrine_Core::getTable('EmailCampaignUserDetails')->findOneByContantInformationIdAndEmailCampaignId($contact['id'], $arguments['campaignId']);
            if($emailCampaignUser) {
              if(is_null($emailCampaignUser->getHardBounceDate()) && is_null($emailCampaignUser->getSoftBounceDate())) {
                $tempSaveFields = $parseVars['saveFields'];
                unset($tempSaveFields[array_search('email', $tempSaveFields)]);
                foreach($tempSaveFields as $key=>$saveField) {
                  if(isset($lineArray[$key]) && $lineArray[$key] != '') {
                    if($saveField == 'complaint_date') {
                      $emailCampaignUser->set($saveField, date('Y-m-d', strtotime($lineArray[$key])));
                    }
                    else {
                      $emailCampaignUser->set($saveField, $lineArray[$key]); 
                    }
                  }
                }
                $emailCampaignUser->save();
                $emailCampaignUserPerformance = Doctrine_Core::getTable('EmailCampaignUserPerformance')->findOneBy('email_campaign_user_details_id', $emailCampaignUser->getId());
                $emailCampaignUserPerformance->set('complaint', 'Yes');
                $emailCampaignUserPerformance->save();
                $emailCampaignUserPerformance->free(true); 
              }
              $emailCampaignUser->free(true);
              $emailCampaignUserPerformance = '';
              $emailCampaignUser = '';
              $contact = '';
              $conn = '';
              unset($emailCampaignUser, $emailCampaignUserPerformance, $contact, $conn);
            } 
          }
        }     
      }
      catch(Exception $e) {
        $this->log($e->getLine());
        $this->log($e->getFile());
        $this->log($e->getMessage());
        exit();
      }

      
    }
  }

}
